/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-29 18:00:27
 * @LastEditors: askmewhat
 * @LastEditTime: 2022-05-31 11:13:12
 */
const http = require('http');
const { default: checkReservedWord } = require('./utils/checkReservedWord');
/**
 * 请求服务
 * @param {String} url
 */
function request(url) {
  return new Promise((resolve, reject) => {
    http.get(url, (res) => {
      if (res.statusCode !== 200) {
        reject(res);
      }
      let rawData = '';
      // eslint-disable-next-line no-return-assign
      res.on('data', (chunk) => rawData += chunk);
      res.on('end', () => {
        var data = JSON.parse(rawData);
        resolve(data);
      });
    });
  });
}

/**
 * 获取所有服务模块地址信息
 */
module.exports.getSwaggerResources = function(url) {
  return request(url);
};

/**
 * 根据服务模块地址获取所有接口信息
 */
module.exports.getApidocs = function(url) {
  return request(url);
};

/**
 * 获取接口下所有的分类
 */
module.exports.getCategories = function(paths) {
  // console.log(paths);
  var pathsKeys = Object.keys(paths);
  var categories = {};
  pathsKeys.forEach((key) => {
    var category = key.split('/')[1];
    category = checkReservedWord(category)
    // var category = key;
    if (!categories[category]) {
      categories[category] = {};
    }
    categories[category][key] = paths[key];
  });
  return categories;
};
